package com.kun.controller.admin;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.kun.controller.BaseController;
import com.kun.entity.Recommended;
import com.kun.result.ExceptionMsg;
import com.kun.result.Response;
import com.kun.result.ResponseData;
import com.kun.service.RecommentService;
import com.kun.util.UploadCosUtil;

/**
 * @description: 
 * @author: KM
 * 2018年5月9日 下午4:53:10
 */
@Controller
@RequiresAuthentication
@RequestMapping("/admin")
public class RecommendAdminController extends BaseController{
	
	@Autowired
	private RecommentService recommentService;
	
	@Value("${application.imgSuffix}")
    private String[] imgSuffix;
	
	//轮播列表页面
	@RequiresPermissions("circlePictureInfo:view")
	@RequestMapping("/recommendList")
	public String recommendList(){
		return "admin/recommendList";
	}
	
	//轮播列表
	@RequiresPermissions("circlePictureInfo:view")
	@RequestMapping("/getRecommend")
	@ResponseBody
	public Map<String,Object> getRecommend(@RequestParam(name = "begin") int begin,
			@RequestParam(name = "length") int length,String jsonString){
		Map<String,Object> map = recommentService.selectAllRecomment(begin, length, jsonString);
		Map<String,Object> m = new HashMap<String,Object>();
		m.put("count",map.get("allRecord"));
		m.put("data",map.get("recommendedList"));
		m.put("code", 0);
		m.put("msg", "");
		return m;
	}
	
	//删除轮播信息
	@RequiresPermissions("circlePicture:delete")
	@RequestMapping(value="deleteRecommend",method=RequestMethod.POST) 
	@ResponseBody
    public Response deleteRecommend(int recommendedid,String circlepicture){
		int a = 1;
		if(circlepicture!=null&&!"".equals(circlepicture)){
			circlepicture = circlepicture.replace("https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com", "");
	    	logger.info("待删除图片："+circlepicture);
			a = UploadCosUtil.deleteCosPic(circlepicture);
		}
    	if(a==0){
    		return result(ExceptionMsg.FAILED);
    	}
		int i = recommentService.deleteRecommendedByKey(recommendedid);
		if(i>0){
			return result(ExceptionMsg.SUCCESS);
		}
		return result(ExceptionMsg.FAILED);
	}
	
	//更新轮播信息
	@RequiresPermissions("circlePicture:update")
	@RequestMapping(value="updateRecommend",method=RequestMethod.POST) 
	@ResponseBody
    public Response updateRecommend(Recommended recommend){
		if(recommend.getRecommendedid()==null){
			return result(ExceptionMsg.FAILED);
		}
		int i = recommentService.updateAllRecommendedByKey(recommend);
		if(i>0){
			return result(ExceptionMsg.SUCCESS);
		}
		return result(ExceptionMsg.FAILED);
	}
	
	//上传轮播图片
	@RequestMapping(value="uploadRecommendImg",method=RequestMethod.POST) 
	@ResponseBody
    public Response uploadRecommendImg(Recommended recommend,HttpServletRequest req,MultipartHttpServletRequest multiReq){
		try {
			MultipartFile  file = multiReq.getFile("file");
			if (file.isEmpty()) {  
	            return result(ExceptionMsg.FileEmpty);
	        }
			// 获取文件名  
	        String fileName = file.getOriginalFilename();  
	        logger.info("上传的文件名为：" + fileName);  
	        // 获取文件的后缀名  
	        String suffixName = fileName.substring(fileName.lastIndexOf("."));  
	        logger.info("上传的后缀名为：" + suffixName);
	        if(!ArrayUtils.contains(imgSuffix, suffixName)){
	        	//不支持的后缀
	        	return result(ExceptionMsg.LimitPictureType);
	        }
	        String cosPath = "/recommendImg/";
	        String fName = "";
	        String img = recommend.getCirclepicture();
	        if(img==null||"".equals(img)){
	        	fName = UUID.randomUUID().toString() + suffixName;
				logger.info("图书图片上传： newname：" + fName);
	        }else{
	        	fName = img;
	        	fName = fName.replace("https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com"+cosPath, "");
	        	UploadCosUtil.deleteCosPic(cosPath + fName);
	        	fName = UUID.randomUUID().toString() + suffixName;
	        }
	        //上传腾讯云cos
			String url = UploadCosUtil.picCOS(file, cosPath, fName);
        	recommend.setCirclepicture(url);
        	if(recommend.getRecommendedid()!=null){
        		recommentService.updateRecommendedByKey(recommend);
        	}else{
        		recommentService.insertRecommended(recommend);//插入轮播信息
        		int recommendId = recommend.getRecommendedid();
        		Map<String,Object> map = new HashMap<String,Object>();
    	        map.put("circlepicture", url);
    	        map.put("recommendid", recommendId);
    	        return new ResponseData(ExceptionMsg.FirstUploadSuccess,map);
        	}
	        return new ResponseData(ExceptionMsg.SUCCESS,url);
		} catch (Exception e) {
			logger.error("failure--"+e.getMessage());
			return result(ExceptionMsg.FAILED);
		}
    }
	
	//插入轮播信息
	@RequiresPermissions("circlePicture:add")
	@RequestMapping(value="insertRecommend",method=RequestMethod.POST) 
	@ResponseBody
    public Response insertRecommend(Recommended recommend){
		int i = recommentService.insertRecommended(recommend);//插入轮播信息
		if(i>0){
			return result(ExceptionMsg.SUCCESS);
		}
		return result(ExceptionMsg.FAILED);
	}

}
